<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="机构名称" prop="organizationName">
        <el-input v-model="queryParams.organizationName" placeholder="请输入机构名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderState">
        <el-select class="w-50" v-model="queryParams.orderState" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in orderState" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="授信时间" prop="creditTimeRange">
        <el-date-picker clearable v-model="queryParams.creditTimeRange" style="width: 300px;" type="daterange"
          value-format="YYYY-MM-DD" placeholder="请选择授信时间范围" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用信时间" label-width="100px" prop="useCreditTimeRange">
        <el-date-picker clearable v-model="queryParams.useCreditTimeRange" type="daterange" value-format="YYYY-MM-DD"
          placeholder="请选择用信时间范围" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          style="width: 300px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['manage:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['manage:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['manage:order:remove']"
        >删除
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['manage:order:export']">导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" fixed="left" align="center" width="220" show-overflow-tooltip prop="orderNo" />
      <el-table-column label="企业名称" align="center" width="200" show-overflow-tooltip
        prop="financingMatch.enterpriseName" />
      <el-table-column label="统一信用代码" align="center" width="200" prop="financingMatch.creditCode" />
      <el-table-column label="金融产品" align="center" width="200" prop="productName" />
      <el-table-column label="金融机构" align="center" width="200" show-overflow-tooltip prop="organizationName" />
      <el-table-column label="派单模式" width="100" align="center" prop="financingMatch.matchType"
        :formatter="(row) => transformDict('matchType', row.financingMatch.matchType)" />
      <el-table-column label="订单状态" width="100" align="center" prop="orderState">
        <template #default="scope">
          <dict-tag :options="orderState" :value="scope.row.orderState" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否用卷" align="center" prop="managerName" /> -->
      <el-table-column label="申请时间" width="120" align="center" prop="createTime" />
      <el-table-column label="授信额度（万元）" align="center" prop="creditAmount" />
      <el-table-column label="授信时间" align="center" prop="creditTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creditTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用信额度（万元）" align="center" prop="loanAmount" />
      <el-table-column label="用信时间" align="center" prop="loanTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.loanTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="还款状态" align="center" prop="paymentState">
        <template #default="scope">
          <dict-tag :options="repaymentState" :value="scope.row.paymentState" />
        </template>
      </el-table-column>
      <el-table-column label="融资顾问" align="center" prop="financialAdvisor" />
      <el-table-column label="客户经理" align="center" prop="managerName" />

      <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
        <template #default="scope">
          <!--          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleAddCredit(scope.row)"
              v-hasPermi="['manage:order:edit']">
            添加授信
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['manage:order:edit']">添加用信
          </el-button>-->
          <el-button link type="primary" icon="search" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改企业融资订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="机构名称" prop="organizationName">
          <el-input v-model="form.organizationName" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderState">
          <el-select v-model="form.orderState" placeholder="请选择订单状态">
            <el-option v-for="dict in orderState" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户经理名称" prop="managerName">
          <el-input v-model="form.managerName" placeholder="请输入客户经理名称" />
        </el-form-item>
        <el-form-item label="授信金额" prop="creditAmount">
          <el-input v-model="form.creditAmount" placeholder="请输入授信金额">
            <template #suffix>
              <span>万元</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="授信时间" prop="creditTime">
          <el-date-picker clearable v-model="form.creditTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择授信时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用信金额" prop="loanAmount">
          <el-input v-model="form.loanAmount" placeholder="请输入用信金额">
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="用信开始时间" prop="loanTime">
          <el-date-picker clearable v-model="form.loanTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择用信开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="融资顾问" prop="financialAdvisor">
          <el-input v-model="form.financialAdvisor" placeholder="请输入融资顾问" />
        </el-form-item>
        <el-form-item label="还款状态" prop="paymentState">
          <el-select v-model="form.paymentState" placeholder="请选择还款状态">
            <el-option v-for="dict in repaymentState" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择订单类型">
            <el-option v-for="dict in whiteOrderType" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!--          <el-button type="primary" @click="submitForm">确 定</el-button>-->
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加授信对话框 -->
    <el-dialog title="添加授信信息" v-model="creditDialogVisible" width="500px" append-to-body>
      <el-form ref="creditFormRef" :model="creditForm" :rules="creditRules" label-width="100px">
        <el-form-item label="授信金额" prop="creditAmount">
          <el-input v-model="creditForm.creditAmount" type="number" placeholder="请输入授信金额">
            <template #suffix>
              <span>万元</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="授信时间" prop="creditTime">
          <el-date-picker v-model="creditForm.creditTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择授信时间"
            style="width: 100%;" />
        </el-form-item>

        <el-form-item label="授信利率(%)" prop="realRate">
          <el-input v-model="creditForm.realRate" type="number" placeholder="请输入授信利率" />
        </el-form-item>

        <el-form-item label="还款方式" prop="paymentType">
          <el-select v-model="creditForm.paymentType" placeholder="请选择还款方式" style="width: 100%;">
            <el-option v-for="dict in repaymentType" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="授信期限(月)" prop="creditPeriod">
          <el-input v-model="creditForm.creditPeriod" type="number" placeholder="请输入授信期限" />
        </el-form-item>

        <el-form-item label="授信状态" prop="creditState">
          <el-radio-group v-model="form.creditState">
            <el-radio v-for="dict in creditState" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="creditForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitCreditForm">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, credit, loan } from "@/api/manage/order"
import { transformDict } from "../../../hooks/dict"

const { proxy } = getCurrentInstance()
const { whiteOrderType, orderState, repaymentState, repaymentType, creditState } = proxy.useDict('whiteOrderType', 'orderState', 'repaymentState', 'repaymentType', 'creditState', 'matchType')

const orderList = ref([])
const open = ref(false)
const creditDialogVisible = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    organizationName: null,
    creditTimeRange: null,
    useCreditTimeRange: null,
    enterpriseName: null,
    orderState: null,
    creditTime: null,
    loanTime: null,
  },
  rules: {},
  creditDialogVisible: false, // 是否显示授信弹窗
  creditForm: {               // 授信表单数据
    creditAmount: undefined,
    creditTime: null,
    realRate: undefined,
    paymentType: '',
    creditPeriod: undefined,
    remark: '',
    creditState: 0, // 默认状态（根据字典）
    organizationId: undefined,
    organizationName: ''
  },
  creditRules: {
    creditAmount: [{ required: true, message: '授信金额不能为空', trigger: 'blur' }],
    creditTime: [{ required: true, message: '授信时间不能为空', trigger: 'change' }],
    realRate: [{ required: true, message: '授信利率不能为空', trigger: 'blur' }],
    paymentType: [{ required: true, message: '请选择还款方式', trigger: 'change' }],
    creditPeriod: [{ required: true, message: '授信期限不能为空', trigger: 'blur' }],
    creditState: [{ required: true, message: '授信状态不能为空', trigger: 'change' }]
  },
  // 字典数据（还款方式、授信状态）
  repaymentType: [], // 还款方式字典
  creditState: []    // 授信状态字典
})

const { queryParams, form, creditForm, rules } = toRefs(data)

/** 查询企业融资订单列表 */
function getList() {
  loading.value = true
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  creditDialogVisible.value = false;
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    machId: null,
    applyId: null,
    orderNo: null,
    orgPath: null,
    organizationId: null,
    organizationName: null,
    organizationType: null,
    logo: null,
    orderState: null,
    managerId: null,
    managerName: null,
    creditAmount: null,
    creditTime: null,
    loanAmount: null,
    loanTime: null,
    financialAdvisor: null,
    paymentState: null,
    createTime: null,
    updateTime: null,
    version: null,
    deleted: null,
    productId: null,
    productName: null,
    amountLimitLower: null,
    amountLimitUpper: null,
    interestRateLimitLower: null,
    interestRateLimitUpper: null,
    loanPeriodLimitLower: null,
    loanPeriodLimitUpper: null,
    mainGuaranteeWay: null,
    secondGuaranteeWay: null,
    productFeature: null,
    repaymentWay: null,
    productOrgPath: null,
    productLogo: null,
    voidedFlag: null,
    siteId: null,
    siteCode: null,
    siteName: null,
    ticketId: null,
    managerPhoto: null,
    orderType: null,
    guaranteeInstitution: null,
    underwritingConfirmationTime: null,
    underwritingStatus: null,
    underwritingTime: null,
    underwritingReason: null
  },
    creditForm.value = {
      creditAmount: undefined,
      creditTime: null,
      realRate: undefined,
      paymentType: '',
      creditPeriod: undefined,
      remark: '',
      creditState: 0,
      organizationId: undefined,
      organizationName: '',
      orderId: undefined
    };
  proxy.resetForm("orderRef")
  proxy.resetForm("creditFormRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加企业融资订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改企业融资订单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除企业融资订单编号为"' + _ids + '"的数据项？').then(function () {
    return delOrder(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

// 打开添加授信弹窗
function handleAddCredit(row) {
  this.resetCreditForm();
  // 自动填充机构ID和名称（来自订单主表）
  this.creditForm.organizationId = row.organizationId;
  this.creditForm.organizationName = row.organizationName;
  // 设置当前订单ID（用于关联）
  this.creditForm.orderId = row.id;

  this.creditDialogVisible = true;
}

// 重置授信表单
function resetCreditForm() {
  this.creditForm = {
    creditAmount: undefined,
    creditTime: null,
    realRate: undefined,
    paymentType: '',
    creditPeriod: undefined,
    remark: '',
    creditState: 0,
    organizationId: undefined,
    organizationName: '',
    orderId: undefined
  };
}

/*function submitCreditForm() {
  proxy.$refs.creditFormRef.validate(valid => {
    if (valid) {
      // 调用后端 API 保存授信信息
      this.$http.post('/api/credit/add', this.creditForm)
          .then(() => {
            this.$message.success('授信信息添加成功');
            this.creditDialogVisible = false;
            // 可选：刷新当前订单列表
            this.getList();
          })
          .catch(err => {
            this.$message.error('保存失败：' + err.message);
          });
    }
  });
}*/

function submitCreditForm() {
  proxy.$refs["creditFormRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        credit(form.value).then(response => {
          proxy.$modal.msgSuccess("授信信息添加成功")
          creditDialogVisible.value = false
          getList()
        })
      }
    }
  })
}

/** 查看按钮操作 */
function handleView(row) {
  const _id = row.id
  getOrder(_id).then(response => {
    form.value = response.data
    open.value = true
  })
}

getList()
</script>
